﻿using System;
using FunctionalCLR.Core;
using Zove.Runtime;

namespace Zove.Runtime {
    public class SolutionSimplifier {
        private RuntimeFactor rf = null;

        public SolutionSimplifier(RuntimeFactor rf) {
            this.rf = rf;
        }

        public string Parse() {
            return this.Parse(this.rf);
        }

        public string Parse(RuntimeFactor rf) {
            if (rf.Status == RuntimeFactorStatus.Input) {
                return rf.Name;
            } else if (rf.Status == RuntimeFactorStatus.Unknown) {
                return "<N/A>";
            }

            DefaultExpressionCompiler eci = new DefaultExpressionCompiler();
            string result = eci.Compile(rf.SolvedRule.Root);
            foreach (RuntimeFactor rff in rf.SolvedRule.Equation.Factors) {
                if (rff.Name == rf.Name) {
                    continue;
                }

                string modified = this.Parse(rff);
                result = Utils.ReplaceString(
                    rff.Name, modified, result);
            }

            return result;
        }
    }
}
